import React from "react";
import {Card, Modal, Table, Button, Tree, Input, message, Form, Popconfirm, Select, Col, Row} from 'antd';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import './Role.css'
import API from "../../api/api";
import RoleForm from './RoleForm'
import UpdateRoleForm from './UpdateRoleForm'
import {config} from "../../util/config";
let {Search} = Input

// import DragM from "dragm/src";
//
// // Modal實現拖動效果
// class BuildTitle extends React.Component {
//     updateTransform = transformStr => {
//         this.modalDom.style.transform = transformStr;
//     };
//     componentDidMount() {
//         this.modalDom = document.getElementsByClassName(
//             "ant-modal-wrap" //modal的class是ant-modal-wrap
//         )[0];
//     }
//     render() {
//         const { title } = this.props;
//         return (
//             <DragM updateTransform={this.updateTransform}>
//                 <div>{ title }</div>
//             </DragM>
//         );
//     }
// }



let {Option} = Select;

export default class Role extends React.Component{
    constructor(props) {
        super(props);
        // store.subscribe(() => {this.setState({visible:store.getState().visible})})
        this.state = {
            roleType:"all",
            result:null,
            status:true,
            data : [],
            buttonVisible:false,
            selectedRowKeys: [], // Check here to configure the default column
            loading: false,
            roleVisible:false,
            roleUpdateVisible:false,
        };
        this.deleteSelected = this.deleteSelected.bind(this)
    }

    status = null;

    text = config.is_delete;

    data = [];

    columns = [
        {
            title: '角色',
            dataIndex: 'name',
            width:150,
            ellipsis:true,
            render: (text, record) => (
                <a onClick={_=>{
                    this.getContent(record);
                }}>
                    {text}
                </a>
            ),
        },
        {
            title: '类型',
            dataIndex: 'type',
            ellipsis:true,
            width:100,
        },
        {
            title: '描述',
            dataIndex: 'desc',
            ellipsis:true,
            width:200
        },
        {
            title: '建立人',
            dataIndex:"createUser",
            ellipsis:true,
            key: 'Options',
            width:200
        },
        {
            title: '建立时间',
            dataIndex:"createTime",
            ellipsis:true,
            key: 'Options',
            width:200
        },
        {
            title: '修改人',
            dataIndex: 'updateUser',
            ellipsis:true,
            width:200,
        },
        {
            title: '修改时间',
            dataIndex: 'updateDate',
            ellipsis:true,
            width:200,
        },
        {
            title: '操作',
            width:180,
            ellipsis:true,
            key: 'Options',
            render: (text, record) => (
                <div>
                    <Button style={{marginRight:"0.5rem"}} type="primary" shape="round" size="middle"   onClick={_=>{this.update(record)}}>
                        修改
                    </Button>
                    <Popconfirm placement="right" title={this.text} onConfirm={_=>{this.delete(record)}} okText="确定" cancelText="取消">
                        <Button type="primary" shape="round" style={{marginRight: "1rem", border: "0.1rem solid #ff7875"}} danger>
                            删除
                        </Button>
                    </Popconfirm>
                </div>
            ),
        },
    ];

    // commitSuccess = () => {
    //     message
    //         .loading('Action in progress..', 2)
    //         .then(() => message.success('Loading finished', 0.6))
    // };
    //
    // getRoles() {
    //     let arr = API.getRole();
    //     if(arr.length>0){
    //         // this.data = arr
    //         let type
    //         if(this.state.roleType=="all"){
    //             this.data = arr;
    //         }
    //         else {
    //             if(this.state.roleType=="clientRole"){
    //                 type = "用户"
    //             }
    //             else type = "管理员"
    //             this.data = arr.filter(item => item.type == type);
    //         }
    //     }
    // }


    getRoles=()=> {
        // message.loading(()=>{
        //     this.getRolesCore();
        // }).then(() => message.success('Loading finished', 0.6))
        this.getRolesCore();
    }

    getRolesCore=()=>{
        let arr = API.getRole();
        if(arr.length>0){
            // this.data = arr
            let type
            if(this.state.roleType=="all"){
                this.data = arr;
            }
            else {
                if(this.state.roleType=="clientRole"){
                    type = "用户"
                }
                else type = "管理员"
                this.data = arr.filter(item => item.type == type);
            }
        }
    }

    getContent(record){

        API.getRoleContent(record.key)
    }

    insert = () => {
        this.setState({
            roleVisible: true,
            status:false
        });
    }

    update = (record) => {
        sessionStorage.setItem("roleId",JSON.stringify(record.key))
        this.setState({
            roleUpdateVisible: true,
            status:false
        });
    }

    delete(record){
        if(API.deleteRole([record.key])=='ok')
        {
            this.setState({
                status: true
            });
        }else {
            this.setState({
                status: false
            });
        }
    }

    cancel = () => {
        // ajax request after empty completing
        this.setState({
            selectedRowKeys: [],
            loading: false,
            status: false
        });
    };

    deleteSelected(){
        if(API.deleteRole(this.state.selectedRowKeys)){
            this.setState({
                status: true
            });
        }else {
            this.setState({
                status: false
            });
        }

    }

    onSelectChange = selectedRowKeys => {
        this.setState({
            selectedRowKeys,
            status: false
        });
    };

    handleCancel = () => {
        if(this.status=='ok'){
            this.status = false
            this.setState({
                roleUpdateVisible: false,
                roleVisible: false,
                status: true
            });
        }else {
            this.setState({
                roleUpdateVisible: false,
                roleVisible: false,
                status:false
            });
        }

    };

    result=(status)=>{
        this.status = status
        if(status=="ok"){
            API.loginToken()
        }
    }

    changeList = (item) => {
        this.setState({roleType:item})
        let type
        if(item=="all"){
            this.data = JSON.parse(sessionStorage.getItem("roles"));
        }
        else {
            if(item=="clientRole"){
                type = "用户"
            }
            else type = "管理员"

            this.data = JSON.parse(sessionStorage.getItem("roles")).filter(item => item.type == type);
        }
        this.setState({status:false})
    }

    getContainer(){
        return "content";
    }

    //
    roles = null;

    search(values){
        if(this.roles==null){
            this.roles = JSON.parse(sessionStorage.getItem("roles"))
        }
        if(this.state.roleType=="all"){
            this.data = this.roles.filter(item => (item.desc && item.desc.indexOf(values)!==-1) || (item.name && item.name.indexOf(values)!==-1));
        }
        else {
            let type;
            if(this.state.roleType=="clientRole"){
                type = "用户"
            }else type = "管理员"
            this.data = this.roles.filter(item => item.type == type && (item.desc && item.desc.indexOf(values)!=-1 || item.name && item.name.indexOf(values)!=-1));
        }
        this.setState({status:false})
    }

    render() {
        //状态如果为true走getRoles()
        if(this.state.status){
            this.getRoles();
        }
        const { loading, selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        return (
            <>
                <div style={{marginBottom:"1rem" }}>
                    <Button type="primary" onClick={this.insert} style={{marginRight:"0.5rem"}}>
                        添加
                    </Button>
                    <Button type="danger" onClick={this.deleteSelected} disabled={!hasSelected} style={{marginRight:"0.5rem"}}>
                        删除选中
                    </Button>
                    <Button type="primary" onClick={this.cancel} disabled={!hasSelected}>
                        取消
                    </Button>
                    <Form
                        style={{display:"inline",marginLeft:"1rem"}}
                        layout={"inline"}
                    >
                        <Form.Item
                            name="roleType"
                            label="角色类型"
                            style={{display:"inline"}}
                        >
                            <Select
                                // placeholder="Select a option and change input text above"
                                onChange={this.changeList}
                                style={{wOptionidth:'6rem'}}
                                defaultValue={"all"}
                            >
                                <Option value="adminRole">管理角色</Option>
                                <Option value="clientRole">用户角色</Option>
                                <Option value="all">所有角色</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item

                            name="keys"
                            label="角色查询"
                            style={{display:"inline"}}
                        >
                            <Search style={{ width: 200 }} allowClear onSearch={(values)=>{this.search(values)}} enterButton />
                        </Form.Item>
                    </Form>
                </div>
                <Table className="decorate" size={"middle"}  style={{ marginTop:0,marginBottom:0 }} rowSelection={rowSelection} columns={this.columns} dataSource={this.data} scroll={{ x: '80vw'}}/>

                <Modal
                    // mask={false}
                    destroyOnClose
                    visible={this.state.roleVisible || this.state.roleUpdateVisible}
                    title={"角色管理"}
                    onCancel={this.handleCancel}
                    footer={[
                        <Button key="back" onClick={this.handleCancel}>退出</Button>
                    ]}
                >
                    {this.state.roleVisible ? <RoleForm result={this.result}></RoleForm>:null}
                    {this.state.roleUpdateVisible ? <UpdateRoleForm result={this.result}></UpdateRoleForm>:null}
                </Modal>
            </>
        );
    }
}






// return (
//     // #40b7c1a6
//     <div>
//         {
//             this.state.buttonVisible == true ?
//                 <>
//                     <Button type="primary" onClick={this.insert}>
//                         insert
//                     </Button>
//                     <Button type="primary" onClick={this.deleteSelected} disabled={!hasSelected}>
//                         deleteAll
//                     </Button>
//                     <Button type="primary" onClick={this.cancel} disabled={!hasSelected}>
//                         cancel
//                     </Button>
//                 </>:null
//         }
//         <Button key={"3"} className={"btn-blur "} style={{marginLeft:"2rem",fontSize: "1rem", border: "none "}} shape="round" size={'large'} onClick={_ => this.changeList("adminRole")}>
//             管理员角色
//         </Button>
//         <Button key={"4"} className={"btn-blur"} style={{fontSize: "1rem", border: "none " }} shape="round" size={'large'} onClick={_ => this.changeList("clientRole")}>
//             用户角色
//         </Button>
//         {
//             this.state.buttonVisible == true ?
//                 <>
//                             <span style={{ marginLeft: 8 }}>
//                                 {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
//                             </span>
//                     <Table rowSelection={rowSelection} columns={this.columns} dataSource={this.state.data} />
//                 </>
//                 :
//                 null
//         }
//
//         <Modal
//             mask={false}
//             destroyOnClose
//             visible={this.state.roleVisible}
//             title={"角色管理"}
//             onOk={this.handleOk}
//             onCancel={this.handleCancel}
//             footer={[
//                 <Button key="back" onClick={this.handleCancel}>
//                     Return
//                 </Button>,
//                 <Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>
//                     Submit
//                 </Button>,
//             ]}
//         >
//             <span>角色名称</span>
//             <Input placeholder="Basic usage" />
//             <span>角色备注</span>
//             <Input placeholder="Basic usage" />
//             <span>角色权限</span>
//             <Authority/>
//         </Modal>
//     </div>
// );




